package com.cbgolf.oa.activity.coupon;

import static com.cbgolf.oa.util.DialogUtil.setWidthHeight;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cbgolf.oa.R;
import com.cbgolf.oa.activity.publiz.MainActivity;
import com.cbgolf.oa.base.BaseActivity;
import com.cbgolf.oa.entity.UserApplyBean;
import com.cbgolf.oa.net.NetCallBack;
import com.cbgolf.oa.net.NetUtils;
import com.cbgolf.oa.net.Web;
import com.cbgolf.oa.net.WebAPI;
import com.cbgolf.oa.user.UserData;
import com.cbgolf.oa.util.AnimaUtil;
import com.cbgolf.oa.util.DateUtil;
import com.cbgolf.oa.util.DensityUtil;
import com.cbgolf.oa.util.DialogUtil;
import com.cbgolf.oa.util.PopUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.widget.autolayout.utils.AutoUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;


/**
 * @author Created by lq on 2017/9/5.
 */

public class CouponCreateSuccessActivity extends BaseActivity {

  //top
  @ViewInject(R.id.topBack_ll)
  private View topBack;
  @ViewInject(R.id.title_tv)
  private TextView topTitle;
  //body
  @ViewInject(R.id.coupon_create_success_parkname_tv)
  private TextView parkNameTv;
  @ViewInject(R.id.coupon_create_success_starttime_tv)
  private TextView startTimeTv;
  @ViewInject(R.id.coupon_create_success_over_time_tv)
  private TextView overTimeTv;
  @ViewInject(R.id.coupon_create_success_money_num_tv)
  private TextView moneyNumTv;
  @ViewInject(R.id.coupon_create_success_limit_money_tv)
  private TextView moneyLimitTv;
  @ViewInject(R.id.coupon_create_success_push_count_tv)
  private TextView pushCountTv;
  @ViewInject(R.id.coupon_create_success_limit_count_tv)
  private TextView limitCountTv;
  //submit
  @ViewInject(R.id.coupon_create_success_push_tv)
  private TextView subMitTv;
  /**
   * var
   */
  private String parkName;
  private long startTime = -1;
  private long overTime = -1;
  private String moneyNum;
  private String moneyLimit;
  private String pushCount;
  private String limitCount;
  private String couponId;
  private boolean isCreate;

  private List<UserApplyBean> listData = new ArrayList<>();


  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.a_coupon_create_success);
  }

  @Override
  protected void findViews() {
    x.view().inject(this);

  }

  @Override
  protected void setViews() {
    parkName = null == UserData.getUser() ? "" : UserData.getUser().getCourseName();
    Intent intent = getIntent();
    startTime = intent.hasExtra("startTime") ? intent.getLongExtra("startTime", -1) : -1;
    overTime = intent.hasExtra("overTime") ? intent.getLongExtra("overTime", -1) : -1;
    moneyNum = intent.hasExtra("moneyNum") ? intent.getStringExtra("moneyNum") : "";
    moneyLimit = intent.hasExtra("moneyLimit") ? intent.getStringExtra("moneyLimit") : "";
    pushCount = intent.hasExtra("pushCount") ? intent.getStringExtra("pushCount") : "";
    limitCount = intent.hasExtra("limitCount") ? intent.getStringExtra("limitCount") : "";
    couponId = intent.hasExtra("id") ? intent.getStringExtra("id") : "";
    isCreate = intent.hasExtra("isCreate") ? intent.getBooleanExtra("isCreate", false) : false;
    if (isCreate) {
      topTitle.setText("创建成功");
    } else {
      topTitle.setText("优惠券发布");
    }
    parkNameTv.setText(parkName);
    if (startTime > 0) {
      startTimeTv.setText(DateUtil.stampToDate(String.valueOf(startTime), DateUtil.formatWithbias));
    }
    if (overTime > 0) {
      overTimeTv.setText(DateUtil.stampToDate(String.valueOf(overTime), DateUtil.formatWithbias));
    }
    moneyNumTv.setText(moneyNum + "元");
    moneyLimitTv.setText("订场满" + moneyLimit + "元可用");
    pushCountTv.setText("共" + pushCount + "张");
    limitCountTv.setText("每人限领" + limitCount + "张");

  }

  @Override
  protected void setListener() {
    topBack.setOnClickListener(v -> finish());
    subMitTv.setOnClickListener(v -> checkInfo());

  }

  @Override
  protected void loadData() {
    super.loadData();

  }

  private void checkInfo() {
    if (!Util.isNetWorkConnected()) {
      Util.showNoNet();
      return;
    }
    if (Util.isNull(couponId)) {
      Util.showNetError();
      return;
    }
    String title = "发布确认";
    String msg = "您是否确认发布优惠券";
    DialogUtil.showMsgDialog(context, title, msg, new DialogUtil.onSubmitListener() {
      @Override
      public void doSubmit() {
        pushCoupon();
      }
    });

  }

  private void pushCoupon() {
    String url = WebAPI.coupons_push_post + "/" + couponId + "/push";
    String token = null == UserData.getUser() ? "" : UserData.getUser().getToken();
    Map<String, String> map = new HashMap<>();
    map.put("token", token);
    AnimaUtil.showLoading(context);
    Web.postOk(url, map, new NetCallBack(response -> {
      AnimaUtil.stopLoading();
//                code = 403;
      if (response.statusCode == 403) {
        selectApplyList();
        return;
      }
      if (200 != response.statusCode) {
        if (!Util.isNull(response.errorMsg)) {
          Util.show(response.errorMsg);
          return;
        }
        Util.showNetError();
        return;
      }
      Intent intent = new Intent(context, CouponPushSuccessActivity.class);
      intent.putExtra("startTime", startTime);
      intent.putExtra("overTime", overTime);
      intent.putExtra("moneyNum", moneyNum);
      intent.putExtra("moneyLimit", moneyLimit);
      startActivity(intent);
      finish();
    }));
  }

  private void selectApplyList() {
    String url = WebAPI.coupons_apply_user_select_get;
    Web.getOK(url, new NetCallBack(response -> {
      if (NetUtils.SUCCESS != response.statusCode) {
        Util.showNetError();
        return;
      }
      if (Util.isNull(response.result)) {
        Util.show("您不具备发布权限,且暂无法申请");
        return;
      }
      List<UserApplyBean> list = null;
      try {
        list = JSON.parseArray(response.result, UserApplyBean.class);
      } catch (Exception e) {
        Util.showNetError();
        return;
      }
      if (null != list && list.size() > 0) {
        List<String> listNames = new ArrayList<>();
        String name;
        for (int i = 0; i < list.size(); i++) {
          name = list.get(i).name;
          if (!Util.isNull(name)) {
            listNames.add(name);
          } else {
            list.remove(i);
          }
        }
        if (listNames.size() == 0) {
          Util.show("您不具备发布权限,且暂无法申请");
          return;
        }
        listData.clear();
        listData.addAll(list);
        showApplyDialog(listNames);
      } else {
        Util.show("您不具备发布权限,且暂无法申请");
        return;
      }
    }));
  }

  String userId;

  private void showApplyDialog(final List<String> list) {
    final Dialog dialog = new Dialog(context, R.style.mDialog);
    View view = getLayoutInflater().inflate(R.layout.dialog_push_apply, null);
    View layout = view.findViewById(R.id.dialog_push_apply_layout_ll);
    TextView cancelTv = (TextView) view.findViewById(R.id.dialog_push_apply_cancel_tv);
    TextView subMitTv = (TextView) view.findViewById(R.id.dialog_push_apply_submit_tv);
    final View userView = view.findViewById(R.id.dialog_push_apply_user_ll);
    final TextView userTv = (TextView) view.findViewById(R.id.dialog_push_apply_username_tv);
    setWidthHeight(layout, DensityUtil.getScreenWidth(), DensityUtil.getScreenHeight());
    AutoUtil.auto(view);
    dialog.setContentView(view);
    userTv.setText(list.get(0));
    userId = listData.get(0).id;
    userView.setOnClickListener(v -> {
      int width = DensityUtil.dp2px(context, 135);
      PopUtil.setPopWidthAndHeight(width, 0);
      PopUtil.setStringData(list);
      PopUtil.showList(context, userView, position -> {
        if (!Util.isNull(list.get(position))) {
          userTv.setText(list.get(position));
        }
        userId = listData.get(position).id;
      });
    });

    cancelTv.setOnClickListener(v -> {
      dialog.cancel();
      dialog.dismiss();
    });
    subMitTv.setOnClickListener(v -> {
      dialog.cancel();
      dialog.dismiss();
      couponApplyPush();

    });
    dialog.show();
  }

  private void couponApplyPush() {

    if (!Util.isNetWorkConnected()) {
      Util.showNoNet();
      return;
    }
    String url = WebAPI.coupons_apply_push_post + "/" + couponId + "/approve";
    Map<String, Object> map = new HashMap<>();
    JSONObject json = new JSONObject();
    json.put("auditUserId", userId);
    json.put("couponId", couponId);
    map.put("dto", json);
    AnimaUtil.showLoading(context);
    Web.postJsonOk(url, map, new NetCallBack(response -> {
      AnimaUtil.stopLoading();
      if (NetUtils.SUCCESS != response.statusCode) {
        if (!Util.isNull(response.errorMsg)) {
          Util.show(response.errorMsg);
          return;
        }
        Util.showNetError();
        return;
      }
      Util.show("申请成功，请耐心等待");
      mStartActivity(MainActivity.class);
      finish();
    }));
  }
}
